package com.showcai.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.showcai.dao.UserDevicRelationMapper;
import com.showcai.dao.UserMapper;
import com.showcai.dao.UserRelationMapper;
import com.showcai.def.Constant;
import com.showcai.module.User;
import com.showcai.module.UserDevicRelation;
import com.showcai.module.UserRelation;
import com.showcai.module.UserThird;
import com.showcai.module.sync.Devic;
import com.showcai.module.sync.Follower;
import com.showcai.module.sync.Member;
import com.showcai.myRunTime.MyRunTimeExcption;
import com.showcai.result.ReturnCode;
import com.showcai.service.MediaPushLogService;
import com.showcai.service.ServiceBase;
import com.showcai.service.UserService;
import com.showcai.service.UserThirdService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Baggio on 2017-11-21.
 */
@Service
public class UserServiceImpl extends ServiceBase implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    UserDevicRelationMapper userDevicRelationMapper;
    @Autowired
    UserRelationMapper userRelationMapper;

    @Autowired
    UserThirdService userThirdService;
@Autowired
MediaPushLogService mediaPushLogService;
    @Override
    public User getUserById(Long userId) throws MyRunTimeExcption {
        logger.info("getUserById");
        if (userId == null) {
            throw new MyRunTimeExcption("userId is null");
        }
        User user = userMapper.getUserById(userId);
        return user;
    }

    @Override
    public User getUserByPhone(String phone) throws MyRunTimeExcption {

        return userMapper.getUserByPhone(phone);
    }

    @Override
    public User getUserBydevicId(String devicId) throws MyRunTimeExcption {
        return userMapper.getUserBydevicId(devicId);
    }

    @Override
    public List<User> getUserList(Integer page, Integer pageSize) throws MyRunTimeExcption {
        List<User> userList = userMapper.getUserList(null);
//        if (page == null || page == 0) {
//            page = Constant.PAGENUM;
//        }
//        System.out.println("pageSize====>>>" + pageSize);
//        // 设置每页记录数
//        if (pageSize == null || pageSize == 0) {
//            pageSize = Constant.PAGESIZENum;
//        }
//        PageHelper.startPage(page, pageSize);
//        List<User> userList = userMapper.getUserList();
//        System.out.println("数据库查询到的用户集合——————"+userList);
//        PageInfo<User> pageinfo = new PageInfo<User>(userList);
        return userList;
    }

    private void updateUser(User user) {
        userMapper.updateUserByPrimaryKeySelective(user);

    }

    @Override
    public void synUser(Member member) throws MyRunTimeExcption {

        UserThird userThird = new UserThird();
        userThird.setType(UserThird.TYPE_APP);
        userThird.setThirdId(member.getMemberId());
        userThird = userThirdService.modifyUserThird(userThird);
        Map<String, String> map = new HashMap<>();
        map.put("phone", member.getMobile());
        User user = userMapper.getUser(map);

        if (user != null) {
            user.setNickName(member.getNickname());
            user.setPicPath(member.getAvatar());
            user.setMemberId(Long.parseLong(member.getMemberId()));
            updateUser(user);

            UserRelation userRelation = new UserRelation();
            userRelation.setUserId(user.getTid());
            userRelation.setThirdId(userThird.getTid());
            UserRelation userRelation1 = userRelationMapper.selectUserRelation(userRelation);
            if (userRelation1 == null) {
                userRelation1 = new UserRelation();
                userRelation1.setUserId(user.getTid());
                userRelation1.setThirdId(userThird.getTid());
                userRelationMapper.insertUserRelation(userRelation1);
            }
            return;
        }
        user = new User();
        user.setCreateTime(new Date());
        user.setMemberId(Long.parseLong(member.getMemberId()));
        user.setNickName(member.getNickname());
        user.setPassWord(member.getPassword());
        user.setPhone(member.getMobile());
        user.setStatus(User.STATUS_VALID);
        user.setPicPath(member.getAvatar());
        userMapper.insertUser(user);

        UserRelation userRelation = new UserRelation();
        userRelation.setUserId(user.getTid());
        userRelation.setThirdId(userThird.getTid());
        userRelationMapper.insertUserRelation(userRelation);


    }

    @Transactional
    @Override
    public void synDevic(Devic devic) throws MyRunTimeExcption {

        String devicId = devic.getDeviceId();
        userDevicRelationMapper.delteUserDevicRelationBydevicId(devicId);

        if(devic.getFollowers().size()==0){
            mediaPushLogService.deleteMediaPushLogBydevicId(devicId);
        }


        for (Follower follower : devic.getFollowers()
        ) {
            UserDevicRelation userDevicRelation = new UserDevicRelation();
            userDevicRelation.setDevicId(devic.getDeviceId());
            Map<String, String> map = new HashMap<>();
            map.put("phone", follower.getMobile());
            User user = userMapper.getUser(map);
            if (user == null) {
                throw new MyRunTimeExcption(ReturnCode.USER_IS_INEXISTENCE);
            }
            userDevicRelation.setUserId(user.getTid());
            userDevicRelation.setAdministrator((follower.getAdmin() == true ? Byte.parseByte("1") : Byte.parseByte("0")));

            userDevicRelationMapper.insertUserDevicRelation(userDevicRelation);

        }

    }

    @Override
    public User addUser(User user) throws MyRunTimeExcption {
        userMapper.insertUser(user);
        return user;

    }

    @Override
    public User getUserByThirdId(String thirdId) {
        return userMapper.getUserByThirdId(thirdId);
    }

    @Override
    public User getUserByMemberId(String memberId) {
        return userMapper.getUserByMemberId(memberId);
    }

    @Override
    public List<Map<String,String>> getDeviceByUser(Map<String, String> map) throws MyRunTimeExcption {
        return userMapper.getDeviceByUser(map);
    }

    @Override
    public PageInfo userList(Map<String, String> map) throws MyRunTimeExcption {
        String pageStr = map.get("page");
        String pageSizeStr = map.get("pageSize");
        Integer page = null;
        Integer pageSize = null;
        if (StringUtils.isNotBlank(pageStr) && StringUtils.isNumeric(pageStr)) {
            page = Integer.parseInt(pageStr);
        }
        if (StringUtils.isNotBlank(pageSizeStr) && StringUtils.isNumeric(pageSizeStr)) {
            pageSize = Integer.parseInt(pageSizeStr);
        }

        if (null == page) {
            page = Constant.PAGENUM;
        }
        if (null == pageSize) {
            pageSize = Constant.PAGESIZENum;
        }
        PageHelper.startPage(page, pageSize);


        List<User> userList = userMapper.getUserList(map);

        PageInfo<User> pageInfo = new PageInfo<>(userList);
        return  pageInfo;
    }
}
